package com.example.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.dto.LoginDTO;
import com.example.dto.RegisterDTO;
import com.example.exception.ServiceException;
import com.example.pojo.User;
import com.example.service.UserService;
import com.example.service.WebService;
import com.example.utils.TokenUtil;
import com.example.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class WebServiceImpl implements WebService {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param loginDTO
     * @return
     */
    public UserVO login(LoginDTO loginDTO) {
        User user = userService.selectByUsername(loginDTO.getUsername());
        //判断用户是否存在，如果不存在则抛出自定义异常
        if (user == null) {
            //500代表后端错误
            throw new ServiceException(500, "用户名或密码错误");
        }
        //对用户输入的密码进行md5加密后
        String newPassWord = SecureUtil.md5(loginDTO.getPassword());
        //进行密码比对
        if (!newPassWord.equals(user.getPassword())) {
            throw new ServiceException(500, "用户名或密码错误");
        }
        //生成token
        String token = TokenUtil.createToken(user.getId().toString(), user.getPassword());
        //将结果封装后返回
        return UserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token)
                .createTime(LocalDateTime.now())
                .build();
    }

    /**
     * 用户注册
     *
     * @param registerDTO
     */
    public void register(RegisterDTO registerDTO) {
        //判断用户名是否已存在
        User user = userService.selectByUsername(registerDTO.getUsername());
        if (user != null) {
            //抛出自定义异常
            throw new ServiceException(500, "用户名已存在");
        }
        user = new User();
        user.setUsername(registerDTO.getUsername());
        //对密码进行md5加密后再存储
        String newPassWord = SecureUtil.md5(registerDTO.getPassword());
        user.setPassword(newPassWord);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userService.save(user);
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    public User getUser() {
        return TokenUtil.getCurrentUser();
    }
}
